package com.example.im.mvp.presenter

import android.app.ProgressDialog
import android.content.Context
import android.util.Log
import com.example.im.entity.FriendOrRoom
import com.example.im.xmpp.IMConnection
import com.example.im.mvp.base.BasePresenter
import com.example.im.mvp.view.IRoomView
import com.example.im.utils.JsonUtils
import com.example.im.utils.LogUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers

class RoomPresenter(mContext: Context, mView: IRoomView?) :
    BasePresenter<IRoomView>(mContext, mView) {

    private var imConnection: IMConnection? = null
    private var dialog: ProgressDialog? = null

    init {
        imConnection = IMConnection.instance!!
        dialog = ProgressDialog(mContext)
        dialog!!.setCanceledOnTouchOutside(false)
        dialog!!.setMessage("请稍候...")
    }

    override fun detachView() {
        super.detachView()
        this.disposable.clear()
    }

    /**
     * 创建群聊
     * */
    fun roomCreate(roomName: String) {
        if (roomName.isEmpty()) {
            getView().onHint("请输入群名")
            return
        }
        val observable = Observable.just(roomName)
            .subscribeOn(Schedulers.io())
            .map {
                imConnection!!.roomCreate(it)
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    if (it.type == 0) {
                        getView().onHint("创建失败")
                    } else {
                        getView().onRoomCreateSuccess(it)
                    }
                },
                {
                    dialog!!.cancel()
                    getView().onHint(it.message!!)
                },
                { dialog!!.cancel() },
                { dialog!!.show() }
            )
        this.disposable.add(observable)
    }

    /**
     * 群聊邀请
     * */
    fun roomInvite(roomName: String, friends: List<FriendOrRoom>) {
        if (friends.isEmpty()) {
            getView().onHint("请选择需要加入的成员")
            return
        }
        val observable1 = Observable.just(roomName)
        val observable2 = Observable.fromIterable(friends)
            .subscribeOn(Schedulers.io())
            .map { it.jid.toString() }
            .toList()
            .toObservable()
        val observable3 = Observable.zip(
            observable1,
            observable2,
            BiFunction<String, List<String>, Boolean> { t1, t2 ->
                imConnection!!.roomInvite(t1, t2)
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    if (it)
                        getView().onRoomInviteSuccess()
                    else
                        getView().onHint("邀请失败")
                },
                { getView().onHint(it.message!!) }
            )
        this.disposable.add(observable3)
    }

    /**
     * 获取群聊用户
     * */
    fun roomUser(room: FriendOrRoom) {
        val observable = Observable.just(room)
            .subscribeOn(Schedulers.io())
            .flatMap {
                Observable.fromIterable(imConnection!!.roomOwners(it.account!!))
            }
            .map {
                imConnection!!.userSearch(it.jid.localpartOrNull.intern())
            }
            .observeOn(AndroidSchedulers.mainThread())
            .filter {
                it.isNotEmpty()
            }
            .flatMap {
                Observable.fromIterable(it)
            }
            .map {
                with(FriendOrRoom(), {
                    this.jid = it.getValues("jid")[0].toString()
                    this.account = it.getValues("Username")[0].toString()
                    this.nickname = it.getValues("Name")[0].toString()
                    this.getFriendOrRoom()
                })
            }
            .toList()
            .toObservable()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    getView().onRoomUserSuccess(it)
                },
                {
                    dialog!!.cancel()
                    getView().onHint(it.message!!)
                },
                { dialog!!.cancel() },
                { dialog!!.show() }
            )
        this.disposable.add(observable)
    }

    /**
     * 踢除成员
     * */
    fun roomKick(roomName: String, friends: ArrayList<FriendOrRoom>) {
        if (friends.isEmpty()) {
            getView().onHint("请选择需要移除的成员")
            return
        }
        val observable = Observable.fromIterable(friends)
            .subscribeOn(Schedulers.io())
            .map {
                imConnection!!.roomKick(roomName, it.jid!!)
            }
            .toList().toObservable()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    getView().onRoomKickSuccess()
                },
                {
                    dialog!!.cancel()
                    getView().onHint(it.message!!)
                },
                { dialog!!.cancel() },
                { dialog!!.show() }
            )
        this.disposable.add(observable)
    }

    /**
     * 退出群聊
     * */
    fun roomLeave(room: FriendOrRoom) {
        val observable = Observable.just(room)
            .subscribeOn(Schedulers.io())
            .map {
                imConnection!!.roomLeave(it.account!!, it.jid!!)
            }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    if (it) getView().onRoomLeaveSuccess()
                    else getView().onHint("退群失败")
                },
                { getView().onHint(it.message!!) }
            )
        this.disposable.add(observable)
    }

}